package cn.big.bigd.biocode.configure;


import cn.big.bigd.biocode.dao.UserDAO;
import cn.big.bigd.biocode.model.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 * Created by Dong Zou on 2016/1/9.
 */
@Component
public class CommonInterceptor extends HandlerInterceptorAdapter {

    @Autowired
    UserDAO userDAO;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null){
            try{
                UserDetails userDetails = (UserDetails) authentication.getPrincipal();
                if (userDetails != null) {
                    String username = userDetails.getUsername();
                    User currentUser = userDAO.findByEmail(username);
                    HttpSession session = request.getSession();
                    session.setAttribute("currentUser", currentUser);
                }
            }catch (Exception e){
                System.out.println("null user");
            }

        }

        return super.preHandle(request, response, handler);
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        String url = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();

        if (modelAndView != null && !modelAndView.getViewName().startsWith("redirect:")) {
            modelAndView.addObject("host", url);
        }

        super.postHandle(request, response, handler, modelAndView);
    }
}
